//
// Created by hjie on 23-5-29.
//

#include <string>
#include <cstddef>
#include <cstdint>
#include <cstdlib>
#include <cstring>
#include <cstdio>
#include <iostream>
#include <string>
#include <thread>
#include <unistd.h>
#include "loop_event.hpp"
#include "./../redis_client.h"
#include "./../redis_message.h"
#include "./../../util/about_time.h"

int main(int argc, char * argv[])
{

    std::cout << "begin" << std::endl;
    LoopEvent loop;

    std::thread loop_thread([&loop](){

        loop.Run();
    });

    std::string ip;
    std::uint16_t port;

    RedisClient client(&loop, "127.0.0.1", 6379);

    int count = 0;
    while(count < 10)
    {
        if (client.CheckClientStatus())
        {
            break;
        }
        usleep(100 * 1000);
        count++;
    }

    while (count < 10)
    {
        std::cout << "127.0.0.1:6379>> ";
        std::string command;

        std::getline(std::cin, command);

        if (command.size() > 0 && command.at(command.size() - 1) == '\n')
        {
            command.erase(command.begin() + command.size() - 1);
        }
        if (command.compare("exit") == 0 || command.compare("quit") == 0)
        {
            break;
        }
        if (command.compare("clear") == 0)
        {
            std::cout.flush();
            system("clear");
            continue;
        }
        if (command.size() == 0)
        {
            continue;
        }
        int64_t  index = client.OperateCommand(command);
        if (index >= 0)
        {
            auto reply = client.GetReplyByIndex(index);
            if (reply->m_reply->IsString())
            {
                std::cout << reply->m_reply->String() << std::endl;
            }
            else if (reply->m_reply->IsNumber())
            {
                std::cout << reply->m_reply->Number() << std::endl;
            }
            else if (reply->m_reply->IsArray())
            {
                int index_number = 0;
                auto arrays = reply->m_reply->Array();
                for (auto & data : arrays)
                {
                    if (data.IsString())
                    {
                        std::cout << index_number++ << ")" << data.String();
                    }
                    else if (data.IsNumber())
                    {
                        std::cout << index_number++ << ")" << data.Number();
                    }
                    std::cout << std::endl;
                }
            }
            else if (reply->m_reply->IsError())
            {
                std::cout << reply->m_reply->Error() << std::endl;
            }
            if (reply)
            {
                client.FreeReplyByIndex(index);
            }
        }
        else
        {
            std::cout << "some error has happen" << std::endl;
            break;
        }
    }

    loop.StopLoopEvent(false);

    loop_thread.join();
    return 0;
}